﻿/*******************************************************
*类名称：WechatMemuManager
*版本号：V1.0.0.0
*作者：成俊杰
*CLR版本：4.0.30319.36264
*创建时间：2017-08-15 20:47:22
*说明：T_WechatMemu管理类
*更新备注：
**********************************************************/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Remoting.Messaging;
using System.Text;
using Wechat.Dao;
using Wechat.Domain;
using Wechat.Dto.Request;
using Wechat.Util.ReturnMessage;
using Wechat.Util.StateCode;
using Wechat.Dto.Response;
using Wechat.Dto.Search;
using Wechat.Dto.Extension;

namespace Wechat.Manager.Implement
{
    /// <summary>
    /// T_WechatMemu
    /// </summary>
    public class WechatMemuManager : GenericManagerBase<WechatMemu>, IWechatMemuManager
    {
        public IWechatMemuRepository WechatMemuRepository { get; set; }
        /// <summary>
        /// 添加微信菜单
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public ResultMessage WechatMemuInsert(WechatMemuRequest request)
        {
            ResultMessage returnMsg = new ResultMessage()
            {
                Status = false,
                Message = "插入数据失败"
            };
            if (this.CurrentRepository is IWechatMemuRepository)
            {
                var WechatMemu = (this.CurrentRepository as IWechatMemuRepository).GetByKey("T_WechatMemu", "WechatName", request.WechatName).FirstOrDefault();

                if (WechatMemu == null)
                {
                    string condition = "SELECT COUNT(1) FROM T_WechatMemu WHERE  IsDeleted<>@IsDeleted AND IsEnable =@IsEnable AND ParentId=@ParentId";
                    var memuFirstCount = Convert.ToInt32((this.CurrentRepository as IWechatMemuRepository).ExecuteScalar(condition, new { IsEnable = 1, IsDeleted = 1, ParentId = request.ParentId }));
                    if (memuFirstCount < 3)
                    {
                        var model = request.ToModel();
                        model.IsEnable = true;
                        var result = (this.CurrentRepository as IWechatMemuRepository).Insert(model);
                        if (result > 0)
                        {
                            returnMsg.Code = (int)EnumApiStateCode.Success;
                            returnMsg.Message = "插入数据成功";
                            returnMsg.Status = true;
                            returnMsg.Data = result;
                        }
                    }
                    else
                    {
                        returnMsg.Message = "当前菜单节点最多可添加3列";
                    }
                }
                else
                {
                    returnMsg.Code = (int)EnumApiStateCode.ParameterValidationFailed;
                    returnMsg.Message = "微信菜单名已存在";
                    returnMsg.Status = false;
                }
            }
            return returnMsg;
        }

        /// <summary>
        /// 获取微信菜单
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public ResultMessage GetMemuList()
        {
            ResultMessage returnMsg = new ResultMessage()
            {
                Status = false,
                Message = "参数校验失败"
            };
            string condition = " SELECT * FROM T_WechatMemu WHERE IsDeleted<>@IsDeleted AND IsEnable =@IsEnable Order By WechatSort";
            var memuList = LoadByCondition(condition, new { IsDeleted = 1, IsEnable = 1 }).ToList();
            if (memuList!=null)
            {
                var treeList = MenuToParseTree(memuList, 0);
                returnMsg.Code = (int)EnumApiStateCode.Success;
                returnMsg.Message = "获取数据成功";
                returnMsg.Status = true;
                returnMsg.Data = treeList;
            }
            else
            {
                returnMsg.Message = "获取数据失败";
            }
            return returnMsg;
        }

        /// <summary>
        /// 同步微信菜单
        /// </summary>
        /// <returns></returns>
        public object SynMemu()
        {
            if (this.CurrentRepository is IWechatMemuRepository)
            {
                string condition = " SELECT * FROM T_WechatMemu WHERE IsDeleted<>@IsDeleted AND IsEnable =@IsEnable Order By WechatSort ";
                var memuList = (this.CurrentRepository as IWechatMemuRepository).LoadByCondition(condition, new { IsDeleted = 1, IsEnable = 1 }).ToList();
                var childList = memuList.Where(memu => (memu.ParentId ?? 0) != 0);
                var firstMemuList = new List<WechatMemu>();
                var objList = new List<object>();
                var sub_buttonItemList = new List<object>();
                if (childList.Count() > 0)
                {
                    #region 有父级菜单进行组合
                    foreach (var parent in memuList)
                    {
                        var buttonItem = new ButtonItem();
                        buttonItem.name = parent.WechatName;
                        sub_buttonItemList = new List<object>();
                        foreach (var child in memuList)
                        {
                            if (parent.WechatId == child.ParentId)
                            {
                                if (child.WechatType == "view")
                                {
                                    var sub_buttonItem = new Sub_buttonView()
                                    {
                                        type = child.WechatType,
                                        name = child.WechatName,
                                        url = child.WechatUrl
                                    };

                                    sub_buttonItemList.Add(sub_buttonItem);
                                }
                                else if (child.WechatType == "click")
                                {
                                    var sub_buttonItem = new Sub_buttonClick()
                                    {
                                        type = child.WechatType,
                                        name = child.WechatName,
                                        key = child.WechatUrl
                                    };

                                    sub_buttonItemList.Add(sub_buttonItem);
                                }

                                firstMemuList.Add(child);
                            }
                        }
                        buttonItem.sub_button = sub_buttonItemList;

                        if (buttonItem.sub_button.Count() > 0)
                        {
                            objList.Add(buttonItem);
                            firstMemuList.Add(parent);
                        }


                    }
                    var secondMemuList = memuList.Except(firstMemuList);
                    foreach (var item in secondMemuList)
                    {
                        if (item.WechatType == "view")
                        {
                            var sub_buttonItem = new Sub_buttonView()
                            {
                                type = item.WechatType,
                                name = item.WechatName,
                                url = item.WechatUrl
                            };

                            objList.Add(sub_buttonItem);
                        }
                        else if (item.WechatType == "click")
                        {
                            var sub_buttonItem = new Sub_buttonClick()
                            {
                                type = item.WechatType,
                                name = item.WechatName,
                                key = item.WechatUrl
                            };

                            objList.Add(sub_buttonItem);
                        }
                    }

                    return new
                    {
                        button = objList
                    };
                    #endregion
                }
                else
                {
                    #region 没有父级菜单的返回数据

                    foreach (var item in memuList)
                    {
                        if (item.WechatType == "view")
                        {
                            var sub_buttonItem = new Sub_buttonView()
                            {
                                type = item.WechatType,
                                name = item.WechatName,
                                url = item.WechatUrl
                            };

                            sub_buttonItemList.Add(sub_buttonItem);
                        }
                        else if (item.WechatType == "click")
                        {
                            var sub_buttonItem = new Sub_buttonClick()
                            {
                                type = item.WechatType,
                                name = item.WechatName,
                                key = item.WechatUrl
                            };

                            sub_buttonItemList.Add(sub_buttonItem);
                        }
                    }
                    return new { button = sub_buttonItemList };
                    #endregion
                }
            }
            return null;

        }

        /// <summary>
        /// 删除数据
        /// </summary>
        /// <param name="idArray"></param>
        /// <returns></returns>
        public ResultMessage WechatMemuDeleteById(string ids)
        {
            ResultMessage returnMsg = new ResultMessage()
            {
                Status = false,
                Message = "参数校验失败"
            };
            if (ids.Length > 0)
            {
                string condition = " UPDATE T_WechatMemu SET IsDeleted=1 WHERE WechatId IN (" + ids + ")";
                var result = ExecuteSql(condition, null);
                if (result > 0)
                {
                    returnMsg.Code = (int)EnumApiStateCode.Success;
                    returnMsg.Message = "删除数据成功";
                    returnMsg.Status = true;
                    returnMsg.Data = result;
                }
                else
                {
                    returnMsg.Message = "删除数据失败";
                }
            }

            return returnMsg;
        }

        /// <summary>
        /// 修改微信菜单
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public ResultMessage WechatMemuUpdateById(WechatMemuRequest request)
        {
            ResultMessage returnMsg = new ResultMessage()
            {
                Status = false,
                Message = "修改数据失败"
            };
            if (this.CurrentRepository is IWechatMemuRepository)
            {
                string condition = @"SELECT COUNT(1) FROM T_WechatMemu WHERE WechatName=@WechatName AND WechatId<>@WechatId
                   AND  IsDeleted<>@IsDeleted  ";//查询除当前菜单外，是否有重名且未删除的菜单
                var WechatMemu = Convert.ToInt32((this.CurrentRepository as IWechatMemuRepository).ExecuteScalar(condition, new { WechatName = request.WechatName, WechatId = request.WechatId, IsDeleted = 1 }));

                if (!(WechatMemu > 0))
                {
                    condition = "SELECT COUNT(1) FROM T_WechatMemu WHERE  IsDeleted<>@IsDeleted AND IsEnable =@IsEnable AND ParentId=@ParentId  AND WechatId<>@WechatId";//查询未删除菜单当前节点是否超过三个
                    var memuFirstCount = Convert.ToInt32((this.CurrentRepository as IWechatMemuRepository).ExecuteScalar(condition, new { IsEnable = 1, IsDeleted = 1, ParentId = request.ParentId, WechatId = request.WechatId }));
                    if (memuFirstCount < 3)
                    {
                        var model = this.CurrentRepository.Get(request.WechatId ?? 0);
                        if (model != null)
                        {
                            model.WechatName = request.WechatName;
                            model.ParentId = request.ParentId;
                            model.WechatType = request.WechatType;
                            model.IsEnable = request.IsEnable ?? model.IsEnable;
                            model.WechatUrl = request.WechatUrl;
                            var result = (this.CurrentRepository as IWechatMemuRepository).Update(model);
                            if (result)
                            {
                                returnMsg.Code = (int)EnumApiStateCode.Success;
                                returnMsg.Message = "修改数据成功";
                                returnMsg.Status = true;
                                returnMsg.Data = result;
                            }
                        }
                    }
                    else
                    {
                        returnMsg.Message = "当前菜单节点最多可添加3列";
                    }
                }
                else
                {
                    returnMsg.Code = (int)EnumApiStateCode.ParameterValidationFailed;
                    returnMsg.Message = "微信菜单名已存在";
                    returnMsg.Status = false;
                }
            }
            return returnMsg;
        }

        /// <summary>
        /// 获取微信菜单分页信息
        /// </summary>
        /// <returns></returns>
        public ResultMessage GetWechatMemuPageData(WechatMemuSearch request)
        {
            ResultMessage resultMsg = new ResultMessage()
            {
                Status = false,
                Message = "查询失败",
                Code = (int)EnumApiStateCode.SystemError,
            };
            var pageData = WechatMemuRepository.GetWechatMemuPageData(request);
            if (pageData != null)
            {
                resultMsg.Status = true;
                resultMsg.Data = pageData;
                resultMsg.Code = (int)EnumApiStateCode.Success;
                resultMsg.Message = "查询成功";
            }
            return resultMsg;
        }

        #region 私有方法
        /// <summary>
        /// 
        /// </summary>
        /// <param name="list"></param>
        /// <param name="parentId"></param>
        /// <returns></returns>
        private List<WechatMemuNode> MenuToParseTree(List<WechatMemu> list, int parentId)
        {
            List<WechatMemuNode> nodeList = new List<WechatMemuNode>();
            List<WechatMemu> ParentMenu = list.Where<WechatMemu>(u => u.ParentId == parentId).ToList();
            foreach (var item in ParentMenu)
            {
                WechatMemuNode node = new WechatMemuNode();
                node.Sort = item.WechatSort;
                node.Type = item.WechatType;
                node.Id = item.WechatId;
                node.ParentId = item.ParentId??0;
                node.Name = item.WechatName;
                node.IsExpand = 1;
                node.Nodes = MenuToParseTree(list, node.Id);
                nodeList.Add(node);
            }
            return nodeList;
        }

      
        #endregion
    }
}